package org.glickr.api.people

import org.glickr.api.FlickrApiMethod
import org.glickr.FlickrPeople
import groovy.util.slurpersupport.GPathResult
import org.glickr.FlickrServiceSyntaxException
import org.glickr.FlickrService
import org.glickr.FlickrServicePluginException
import org.glickr.FlickrServiceApiException

/* ----------------------------------------------------------------------------------------------------
REQUEST: flickr.people.findByEmail
INFO: Return a user's NSID, given their email address

AUTHENTICATION: This method does not require authentication.

ARGUMENTS:
api_key (Required): Your API application key.
find_email (Required): The email address of the user to find  (may be primary or secondary).

EXAMPLE RESPONSE:
<user nsid="12037949632@N01">
  <username>Stewart</username>
</user>
---------------------------------------------------------------------------------------------------- */


class peopleFindByEmail implements FlickrApiMethod {
    //
    //  API METHOD
    //
    static final String apiMethod = 'flickr.people.findByEmail'

    //
    //  VALIDATOR
    //
    Closure validatorClosure = { FlickrPeople people ->
        if (!people || !people?.email) { return [validated:false, message:"Required parameter 'FlickrPeople.email' is missing"] }
        return [validated:true]
    }

    //
    //  PARAMS
    //
    Closure paramsClosure = { FlickrPeople people ->
        [find_email:people.email]
    }

    //
    //  PROCESSOR
    //
    Closure processorClosure = { GPathResult response, FlickrPeople people ->
        people.id       = response.user.@id.toString()
        people.nsid     = response.user.@nsid.toString()
        people.username = response.user.username.toString()
        return people
    }

    //
    //  ERROR CODES
    //
    Closure errorsClosure = { GPathResult response ->
        if (response.err.@code.toInteger() == 1) { return null }      // user not found

        // recoverable errors
        if ([100,105,116].contains(response.err.@code.toInteger())) {
            return new FlickrServiceApiException(response)
        } else {
            return new FlickrServicePluginException(response)
        }
    }
}
